<template>
  <ul>
    <li>
      <el-button size="large" text :icon="Edit" @click="dialogFormVisible = true;">修改信息</el-button>
    </li>
    <li>
      <el-button size="large" text :icon="SwitchButton" @click="logout">退出登录</el-button>
    </li>
  </ul>

  <el-dialog v-model="dialogFormVisible" title="修改个人信息" center>
    <el-form ref="formRef" :model="data.form" >
      <el-form-item label="用户名" :label-width="formLabelWidth">
        <el-input v-model="username" autocomplete="off" disabled/>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email" :rules="emailRules">
        <el-input v-model="email"></el-input>
      </el-form-item>
      <el-form-item label="手机号" :label-width="formLabelWidth" prop="mobile" :rules="mobileRules">
        <el-input v-model="mobile"></el-input>
      </el-form-item>
      <el-form-item label="头像" :label-width="formLabelWidth" prop="">
        <el-upload
            class="avatar-uploader"
            action=""
            :http-request="handlerUploadAvatar"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            accept=".jpg,.jpeg,.png"
        >
          <el-image v-if="avatar" :src="avatar" class="avatar" @error="loadFail" />
<!--          <img v-if="avatar" :src="avatar" class="avatar"/>-->
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handlerSubmit">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup >
  import { ref, reactive, toRefs, onMounted, watchEffect } from 'vue';
  import { Edit, SwitchButton } from '@element-plus/icons-vue';
  import { updateEmailAndMobile, uploadAvatar } from '@a/account';
  import router from '@/router'
  import cookies from "@u/cookies";

  let dialogFormVisible = ref(false)
  const formRef = ref(null);
  const formLabelWidth = '140px'

  const props = defineProps({
    id: Number,
    username: String,
    email: String,
    mobile: String,
    avatar: String
  })

  let data = reactive({
    form: {
      id: 0,
      username: '',
      email: '',
      mobile: ''
    }
  })
  const { id, username, email, mobile } = toRefs(data.form);

  const emailRules = [
    // { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
  const mobileRules = [
    { pattern: /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]

  const userID = cookies.getCookie("id");
  const avatar = ref(props.avatar);


  /** 上传头像 */
  const handlerUploadAvatar = (file) => {
    const requestData = new FormData();
    requestData.append('avatar', file.file);
    uploadAvatar(userID, requestData)
      .then(response => {
        avatar.value = response.data.url;
        ElMessage.success('图片上传成功!');
      })
      .catch(error => {
        ElMessage.error(error.response.data.msg || error.response.statusText)
      })
  }

  /** 判断图片大小，不能超过2MB*/
  const beforeAvatarUpload = (fileDate) => {
    if(fileDate && fileDate.size > 1024 * 1024 * 2){
      ElMessage.error('图片大小不能超过2MB');
      return false;
    }
  }

  /** el-image加载失败事件  */
  const loadFail = () => {
    avatar.value = '';
  }

  // 监听父组件传值
  watchEffect(() =>{
    console.log('监听父组件props', props);
    data.form.id = props.id;
    data.form.username = props.username;
    data.form.email = props.email;
    data.form.mobile = props.mobile;
    avatar.value = props.avatar;
  })

  const logout =() => {
    cookies.removeCookie('id');
    cookies.removeCookie('username');
    cookies.removeCookie('token');
    cookies.removeCookie('refresh');
    cookies.removeCookie('csrftoken');
    router.push({ path: "/"});
  }


  const emit = defineEmits(['getInformation']);
  // 提交表单
  const handlerSubmit = () => {
    formRef.value.validateField(['email', 'mobile'], valid => {
      if(valid) {
        const requestData = {
          email: data.form.email,
          mobile: data.form.mobile
        }
        updateEmailAndMobile(userID, requestData)
            .then(response => {
              ElMessage.success('修改成功');
              // 子组件调用父组件方法，重新查询用户信息
              emit('getInformation');
              dialogFormVisible.value = false;
            })
            .catch(error => {
              ElMessage.error(error.response.msg || error.response.statusText)
            })
      }else {
        ElMessage.error('请核对邮箱和手机号格式!');
        return false;
      }
    })
  }
</script>

<style scoped>
  .el-dialog__body {
    z-index: 100;
  }

  /* 图片上传框样式 */
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>